var express = require('express');
var path = require('path');
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var userList = [];

//首页路由
app.get("/" , function(req , res){
  res.sendfile("index.html");
});
//资源路径
app.use(express.static(path.join(__dirname, "./app/public")));
//io
io.on("connection" , function(socket){
  //断开连接回调事件(这个事件是在连接后的回调函数内)
  socket.on("disconnect" , function(){
    //删除用户
    var data = deleteJson(userList , socket.id);
    if(data){
      io.emit("userList" , {
        userList:userList,
        name:data.name,
        type:"offline"
      });
    };
  });
  //登陆
  socket.on("login" , function(data , callback){
    //检测名称是否存在
    if(isName(userList , data.name)){
      callback(false);
    }else{
      callback(true);
      data.id = socket.id;
      userList.push(data);
      //上线通知
      io.emit("userList" , {
        userList:userList,
        name:data.name,
        type:"online"
      });
    };
  });
  //接受信息
  socket.on("testMsg" , function(msgData){
    //广播信息
    socket.broadcast.emit("msgAll" , msgData);
  });
});
//删除json函数
function deleteJson(data , id){
  var arr = "";
  for(var i in data){
    if(data[i]['id'] === id){
      arr = data[i];
      data.splice(i , 1);
      return arr;
    };
  };
};
//判断name是否存在
function isName(data , name){
  for(var i in data){
    if(data[i]['name'] === name){
      return true;
    };
  };
};
//端口监听
http.listen(3000, function (){
  console.log('启动成功请访问http://location:3000');
});
